package org.open.sharedRadar;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.open.sharedRadar.Road;
import org.open.sharedRadar.RoadProvider;


import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class FindCar extends MapActivity
{
    /** Called when the activity is first created. */
    MapView harta = null;
    MyLocationOverlay locatiaMea = null;
    public static double lat;
    public static double lng;
    LocationManager locManager =null;
    LocationListener locListener = null;
    final DBAdapter myDBAdapter = new DBAdapter(this);
    Cursor locatii;
    private Road mRoad;
    public String observatieLocatieDeAfisat;    
   public static double toLat;
   public static double toLng;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.findcar);
       // MapView harta = (MapView) findViewById(R.id.harta);
        harta = (MapView) findViewById(R.id.harta);
        
        harta.setBuiltInZoomControls(true);
        //harta.getController().setCenter(new GeoPoint((int) (47.157109 * 1E6), (int) (27.588329 * 1E6)));
        harta.getController().setZoom(15);
        
        locatiaMea = new MyLocationOverlay(this, harta);
        harta.getOverlays().add(locatiaMea);
        
        
        Button btnSaveLocation =(Button) findViewById(R.id.btnAddLocation); 
        btnSaveLocation.setOnClickListener(new OnClickListener(){
        	
        	public void onClick(View v){
        		Intent iAdd = new Intent(FindCar.this, AddLocation.class);
        		startActivity(iAdd);
        	}
        });
        
        Button btnFindMyCar =(Button) findViewById(R.id.btnFindMyCar); 
        
        btnFindMyCar.setOnClickListener(new OnClickListener(){        	
        	public void onClick(View v){
        		myDBAdapter.open();
        		locatii = myDBAdapter.getAllLocatii();	

        		
				Locatie locatieCurenta;
				locatii.moveToLast();	
								
				if (locatii.getCount()>=1 && lat > 0.00 && lng > 0.00)
				{
					locatieCurenta = new Locatie();
					
					locatieCurenta.setId(Integer.valueOf(locatii.getInt(0)));
					locatieCurenta.setPozLong(locatii.getString(1));
					locatieCurenta.setPozLat(locatii.getString(2));
					locatieCurenta.setObservatie(locatii.getString(3));
	        		toLat = Double.parseDouble(locatieCurenta.getPozLat().toString());
	        		toLng = Double.parseDouble(locatieCurenta.getPozLong().toString());
	        		observatieLocatieDeAfisat = locatieCurenta.getObservatie().toString();
	        		locatii.close();
	        		String url = RoadProvider
	                        .getUrl(lat, lng, toLat, toLng);
	        		InputStream is = getConnection(url);
	        		
	        		mRoad = RoadProvider.getRoute(is);
	        		mHandler.sendEmptyMessage(0);      		
				}
				else
				{
					Toast.makeText(getBaseContext(), "Nu aveti nicio locatie memorata!", Toast.LENGTH_LONG).show();
				}
				myDBAdapter.close();
        	}
        });		        
        
        harta.postInvalidate();
        
        locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        locListener = new LocationListener(){
        	public void onLocationChanged(Location location){
        		afiseazaLocatie(location);
        	}
        	
        	public void onProviderDisabled(String provider){
        		
        	}
        	public void onProviderEnabled(String provider){
        		
        	}
        	
        	public void onStatusChanged(String provider, int status, Bundle extras){
        		
        	}
        };
    }
	
	@Override
	protected boolean isLocationDisplayed() {		
		return locatiaMea.isMyLocationEnabled();
	}

	@Override
	protected boolean isRouteDisplayed() {		
		return true;
		//return locatiaMea.isMyLocationEnabled();
	}
	@Override
	public void onResume(){
		super.onResume();
		Location ultimaLocatieCunoscuta = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		afiseazaLocatie(ultimaLocatieCunoscuta);
		
		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
		
		locatiaMea.enableMyLocation();
		locatiaMea.runOnFirstFix(new Runnable(){
			public void run(){
				harta.getController().setCenter(locatiaMea.getMyLocation());
			}
		});
	}
	@Override
	public void onPause(){
		super.onPause();
		locManager.removeUpdates(locListener);
		locatiaMea.disableMyLocation();
	}
	
	private void afiseazaLocatie(Location locatie){
		if (locatie != null){
			///double lat = locatie.getLatitude();
			lat = locatie.getLatitude();
			//double lng = locatie.getLongitude();
			lng = locatie.getLongitude();
			GeoPoint pctLocatie = new GeoPoint((int)(lat * 1000000),
					(int) (lng * 1000000));
			//Toast.makeText(getBaseContext(), "Noua locatie: lat [" + lat + "] long [" + lng + "]", Toast.LENGTH_SHORT).show();
			harta.getController().animateTo(pctLocatie);
			
		}
	}
	public static String getLng(){
		return Double.toString(lng);
	}
	
	public static String getLat(){
		return Double.toString(lat);
	}
	
	 private InputStream getConnection(String url) {
         InputStream is = null;
         try {
                 URLConnection conn = new URL(url).openConnection();
                 is = conn.getInputStream();
         } catch (MalformedURLException e) {
                 e.printStackTrace();
         } catch (IOException e) {
                 e.printStackTrace();
         }
         return is;
	 }
	 Handler mHandler = new Handler() {
         public void handleMessage(android.os.Message msg) {
                 TextView textView = (TextView) findViewById(R.id.descriptionTextView);
                 textView.setTextColor(Color.BLACK);
                 textView.setText(observatieLocatieDeAfisat + "\n" + mRoad.mName + " " + mRoad.mDescription);
                 MapOverlay mapOverlay = new MapOverlay(mRoad, harta);
                 List<Overlay> listOfOverlays = harta.getOverlays();
                 listOfOverlays.clear();
                 listOfOverlays.add(mapOverlay);                                    
                 harta.invalidate();
         };
 };
	


	class MapOverlay extends com.google.android.maps.Overlay {
	    Road mRoad;
	    ArrayList<GeoPoint> mPoints;
	    public GeoPoint geoPoint;
	    
	    public MapOverlay(Road road, MapView mv) {
	            mRoad = road;
	            if (road.mRoute.length > 0) {
	                    mPoints = new ArrayList<GeoPoint>();
	                    for (int i = 0; i < road.mRoute.length; i++) {
	                            mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
	                                            (int) (road.mRoute[i][0] * 1000000)));
	                    }
	                    int moveToLat = (mPoints.get(0).getLatitudeE6() + (mPoints.get(
	                                    mPoints.size() - 1).getLatitudeE6() - mPoints.get(0)
	                                    .getLatitudeE6()) / 2);
	                    int moveToLong = (mPoints.get(0).getLongitudeE6() + (mPoints.get(
	                                    mPoints.size() - 1).getLongitudeE6() - mPoints.get(0)
	                                    .getLongitudeE6()) / 2);
	                    GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong);
	
	                    MapController mapController = mv.getController();
	                    mapController.animateTo(moveTo);
	                    mapController.setZoom(18);
	                  
	            }
	    }
	
	    @Override
	    public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
	            super.draw(canvas, mv, shadow);
	            drawPath(mv, canvas);	            
	            return true;
	    }
	
	    public void drawPath(MapView mv, Canvas canvas) {
	            int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
	            Paint paint = new Paint();
	            paint.setColor(Color.RED);
	            paint.setStyle(Paint.Style.STROKE);
	            paint.setStrokeWidth(3);
	            for (int i = 0; i < mPoints.size(); i++) {
	                    Point point = new Point();
	                    mv.getProjection().toPixels(mPoints.get(i), point);
	                    x2 = point.x;
	                    y2 = point.y;
	                    if (i > 0) {
	                            canvas.drawLine(x1, y1, x2, y2, paint);
	                    }
	                    x1 = x2;
	                    y1 = y2;
	            }
	            Point screenPts = new Point();
		    	geoPoint = new GeoPoint((int)(lat*1000000.0), (int)(lng*1000000.0));
		    	mv.getProjection().toPixels(geoPoint, screenPts);
		    	Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.flag_red);            
		        canvas.drawBitmap(bmp, screenPts.x - 20, screenPts.y - 25, null); 
		        
		        Point screenPts2 = new Point();
		    	geoPoint = new GeoPoint((int)(toLat*1000000.0), (int)(toLng*1000000.0));
		    	mv.getProjection().toPixels(geoPoint, screenPts2);
		    	Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.flag_green);            
		        canvas.drawBitmap(bmp2, screenPts2.x - 20, screenPts2.y-25, null);  
	    }
	}
}